#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFFER_SIZE 1024
#define SERVER_IP "127.0.0.1"
#define PORT 8888

int main()
{
    int client_socket;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];
    char search_query[BUFFER_SIZE];

    // 创建套接字
    printf("开始创建客户端套接字...\n");
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1)
    {
        perror("套接字创建失败");
        printf("创建客户端套接字失败，程序退出。\n");
        exit(EXIT_FAILURE);
    }
    printf("客户端套接字创建成功，套接字描述符为：%d\n", client_socket);

    // 准备服务器地址结构
    printf("开始准备服务器地址结构...\n");
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    server_addr.sin_port = htons(PORT);
    printf("服务器地址结构准备完成。\n");

    // 连接到服务器
    printf("开始连接到服务器 %s:%d...\n", SERVER_IP, PORT);
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("连接失败");
        printf("连接到服务器失败，程序退出。\n");
        exit(EXIT_FAILURE);
    }
    printf("成功连接到服务器 %s:%d。\n", SERVER_IP, PORT);

    // 获取用户搜索请求
    printf("请输入搜索查询（输入'q'或'Q'退出）: ");
    if (fgets(search_query, BUFFER_SIZE, stdin) == NULL)
    {
        perror("读取用户输入失败");
        printf("读取用户搜索请求失败，关闭套接字并退出程序。\n");
        close(client_socket);
        exit(EXIT_FAILURE);
    }

    // 检查是否退出
    if (strcmp(search_query, "q\n") == 0 || strcmp(search_query, "Q\n") == 0)
    {
        printf("用户请求退出，关闭套接字并退出程序。\n");
        close(client_socket);
        return 0;
    }

    // 发送搜索请求到服务器
    printf("开始向服务器发送搜索请求：%s\n", search_query);
    if (send(client_socket, search_query, strlen(search_query), 0) == -1)
    {
        perror("发送失败");
        printf("向服务器发送搜索请求失败，关闭套接字并退出程序。\n");
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    printf("搜索请求已成功发送到服务器。\n");

    // 接收并显示搜索结果
    printf("开始接收并显示搜索结果...\n");
    int results_found = 0;
    while (1)
    {
        memset(buffer, 0, BUFFER_SIZE);
        ssize_t bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
        if (bytes_received <= 0)
        {
            printf("接收数据失败或连接已关闭，停止接收。\n");
            break;
        }

        // 检查是否是结束标记
        if (strstr(buffer, "END_OF_RESULTS") != NULL)
        {
            printf("接收到结束标记，停止接收。\n");
            break;
        }

        printf("%s", buffer);
        results_found = 1;
    }

    if (!results_found)
    {
        printf("未找到匹配的搜索结果。\n");
    }

    // 关闭套接字
    printf("关闭客户端套接字，程序结束。\n");
    close(client_socket);
    return 0;
}